import re
import os
from channels.channels import Channel


class ReadFile2Lines_NLSm(Channel):
    """
    Read file_path and convert to lines.
    File format: text
        我爱北京天安门，因为这是我的祖国的象征。
        我爱你。
    """
    required = ['file_path']
    send = ['lines']

    def char_map(self):
        """符号映射"""
        # regex_flags = r'/^[\u4e00-\u9fa5_a-zA-Z0-9\s\·\~\！\@\#\￥\%\……\&\*\（\）\——\-\+\=\【\】\{\}\、\|\；\‘\’\：\“\”\《\》\？\，\。\、\`\~\!\#\$\%\^\&\*\(\)\_\[\]{\}\\\|\;\'\'\:\"\"\,\.\/\<\>\?]+$/'
        # seg_flags = r'/^[u4e00-u9fa5_a-zA-Z0-9s·~！@#￥%……&*（）——-+=【】{}、|；‘’：“”《》？，。、`~!#$%^&*()_[]{}|;\'\':"",./<>?]+$'
        # seg_flags = r'/^[u4e00-u9fa5_a-zA-Z0-9s·~！@#￥%……&*（）——-+=【】{}、|；‘’：“”《》？，。、`~!#$%^&*()_[]{}|;\'\':"",./<>?]+$'

        map_dict = {
            '，': r'\^\[\]\·\~\@\￥\%\…\&\*\（\）\—\-\+\=\【\】\{\}\、\|\；\‘\’\：\“\”\《\》\，\、\`\~\ \#\$\%\^\&\(\)\_\{\}\|\; \\\'\:\"\,\/\<\>\]\$',
            '。': r'\！\。\!\.',
            '？': r'\？\?',
        }
        map_dict_bat = {
            '。': r'！。!.',
            '？': r'？?',
        }
        return map_dict, map_dict_bat

    @staticmethod
    def execute(args={}, meta={}, lines=[], **kwargs):
        file_path = args.get('file_path', '')
        with open(file_path, 'r', encoding='utf-8') as fr:


            # map_dict = ReadFile2Lines_NLSm().char_map()
            # content = fr.read()
            # for key, reg in map_dict.items():
            #     content, n = re.subn(r'['+ reg +']', key, content)

            # segL_res = re.split(r'['+''.join(map_dict.keys())+'\\n]', content)

            # lines_news = []
            # line_limit = args.get('para_limit', [0, 20000])
            # for index, res in enumerate(segL_res):
            #     # bar show
            #     args.bar_show(index, len(segL_res))

            #     line_len = len(res)
            #     if line_len >= line_limit[0] and line_len <= line_limit[1]:
            #         lines_news.append(res)
            content = fr.read()
            map_dict, map_dict_bat = ReadFile2Lines_NLSm().char_map()
            # text char handle
            print('Compile puncution')
            chars = re.findall(r'[^\u4e00-\u9fa5]', fr.read())
            chars_set = set(chars)
            map_dict['，'] += ''.join(chars_set - set(map_dict_bat['。']) - set(map_dict_bat['？']))
            fr.seek(0)

            keys = map_dict.keys()
            line_limit = args.get('para_limit', [0, 20000])

            for key, reg in map_dict.items():
                content, n = re.subn(r'[' + reg + ']', key, content)
            # segL_res = re.split(r'['+''.join(map_dict.keys())+']', line) # Split by symbol

            lines = content.split('\n')
            # print(len(lines))

            lines_news = []
            temp = ''
            # replace
            for index, line in enumerate(lines):
                if line.strip():
                    # print(index, ': line-->', line)
                    for i in line:
                        temp += i
                        if i in keys:
                            line_len = len(temp)
                            if line_len >= line_limit[0] + 1 and line_len <= line_limit[1] + 1:
                                # print(temp)
                                lines_news.append(temp[:-1])
                                temp = ''
                            if i in ['！', '？', '。']:
                                temp = ''

                # bar show
                args.bar_show(index, len(lines))

            return {
                'lines': lines_news
            }
